using Microsoft.Extensions.Logging;
using SumerCoreDevOps.ExecuteNodeApi.Services;
using SumerCoreDevOps.Infrastructure.Libraries;
using SumerCoreDevOps.Infrastructure.Security;
using SumerCoreDevOps.Shared.Models.Messages;
using System.Text.Json;

namespace SumerCoreDevOps.ExecuteNodeApi.Handlers;

/// <summary>
/// Kubernetes 部署处理器
/// </summary>
public class DeployK8sHandler : IStepHandler
{
    private readonly ILogger<DeployK8sHandler> _logger;
    private readonly ILoggerFactory _loggerFactory;
    private readonly IConfiguration _configuration;
    private readonly TaskExecutor _taskExecutor;

    public DeployK8sHandler(
        ILogger<DeployK8sHandler> logger,
        ILoggerFactory loggerFactory,
        IConfiguration configuration,
        TaskExecutor taskExecutor)
    {
        _logger = logger;
        _loggerFactory = loggerFactory;
        _configuration = configuration;
        _taskExecutor = taskExecutor;
    }

    public async Task<StepExecutionResult> ExecuteAsync(WorkflowStepDispatchMessage message)
    {
        try
        {
            var config = JsonSerializer.Deserialize<K8sDeployConfig>(message.StepConfig);

            if (config == null)
            {
                return new StepExecutionResult
                {
                    Success = false,
                    ErrorMessage = "Kubernetes 部署配置无效"
                };
            }

            // 获取 Kubernetes 凭证
            string? kubeConfigPath = null;
            string? clusterUrl = null;
            string? token = null;

            if (message.EncryptedCredentials.TryGetValue(Shared.Enums.CredentialType.Kubernetes, out var encryptedCred))
            {
                try
                {
                    // 解密凭证
                    var decryptedJson = EncryptionHelper.Decrypt(encryptedCred);
                    var k8sCredential = JsonSerializer.Deserialize<KubernetesCredential>(decryptedJson);

                    if (k8sCredential != null)
                    {
                        if (!string.IsNullOrEmpty(k8sCredential.KubeConfig))
                        {
                            // 如果提供了 kubeconfig 内容，写入临时文件
                            var tempKubeConfig = Path.Combine(Path.GetTempPath(), $"kubeconfig-{Guid.NewGuid()}.yaml");
                            await File.WriteAllTextAsync(tempKubeConfig, k8sCredential.KubeConfig);
                            kubeConfigPath = tempKubeConfig;
                            _logger.LogInformation("使用提供的 kubeconfig，已写入临时文件: {Path}", tempKubeConfig);
                        }
                        else
                        {
                            // 使用 Cluster URL 和 Token
                            clusterUrl = k8sCredential.ClusterUrl;
                            token = k8sCredential.Token;
                            _logger.LogInformation("使用 Cluster URL 和 Token 连接 K8s");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogWarning(ex, "Kubernetes 凭证解密失败，将使用默认 kubeconfig");
                }
            }

            // 如果没有从凭证获取，则使用环境变量或默认路径
            kubeConfigPath ??= Environment.GetEnvironmentVariable("KUBECONFIG") ?? Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".kube", "config");

            // 创建 Kubernetes 客户端
            KubernetesLibrary k8sLib;
            if (!string.IsNullOrEmpty(clusterUrl) && !string.IsNullOrEmpty(token))
            {
                k8sLib = new KubernetesLibrary(_loggerFactory.CreateLogger<KubernetesLibrary>(), clusterUrl, token);
            }
            else
            {
                k8sLib = new KubernetesLibrary(_loggerFactory.CreateLogger<KubernetesLibrary>(), kubeConfigPath);
            }

            // 订阅 K8s 日志事件，转发到控制面板
            k8sLib.OnLog += async (logMessage, logLevel) =>
            {
                await _taskExecutor.SendLogAsync(message.TaskId, message.StepId, logMessage, logLevel);
            };

            // 部署服务
            var success = await k8sLib.DeployServiceAsync(
                config.ServiceName!,
                config.ImageName!,
                config.Namespace ?? "default",
                config.Replicas ?? 1,
                config.Labels,
                config.EnvironmentVars);

            if (success)
            {
                return new StepExecutionResult
                {
                    Success = true,
                    Progress = 100,
                    OutputContext = new Dictionary<string, string>
                    {
                        ["K8S_SERVICE"] = config.ServiceName!,
                        ["K8S_NAMESPACE"] = config.Namespace ?? "default",
                        ["K8S_IMAGE"] = config.ImageName!
                    }
                };
            }
            else
            {
                return new StepExecutionResult
                {
                    Success = false,
                    ErrorMessage = "Kubernetes 部署失败"
                };
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Kubernetes 部署处理器执行失败");
            return new StepExecutionResult
            {
                Success = false,
                ErrorMessage = ex.Message
            };
        }
    }
}

public class K8sDeployConfig
{
    public string? ServiceName { get; set; }
    public string? ImageName { get; set; }
    public string? Namespace { get; set; }
    public int? Replicas { get; set; }
    public Dictionary<string, string>? Labels { get; set; }
    public Dictionary<string, string>? EnvironmentVars { get; set; }
}
